angular.module('howMuch.controllers', ['howMuch.services', "ngFilterExtensions", "ui.bootstrap", "ngGrid", "ui.tinymce", "multi-select"]);

/*angular.module('howMuch.controllers').config([
    '$translateProvider',
    function($translateProvider) {
        $translateProvider.useStaticFilesLoader({
            prefix: '/lang/',
            suffix: '.json'
        });

        $translateProvider.preferredLanguage('en');
    }
]);*/

angular.module('howMuch.controllers').controller('DashboardController', [
    '$scope',
    function($scope){
        setMenuItemActive("dashboard");
    }
]);

/*--------------- Customer Controller ------------------*/
angular.module('howMuch.controllers').controller('CustomerController', [
    '$scope', '$http', '$filter', 'CustomerService', 'HowMuchUtilityService',
    function($scope, $http, $filter, CustomerService, HowMuchUtilityService){
        var self = this;
    
        self.scope = $scope;
        self.http = $http;
        self.filter = $filter;

        self.scope.items = [];
        self.scope.isFormOpen = false;
        self.scope.formTitle = self.filter('translate')("Add a new customer");
        self.scope.customerModel = {
            name: "",
            address: {
                street: "",
                zipCode: "",
                city: ""
            },
            piva: "",
            eur_h: ""
        };

        self.scope.isInEditMode = false;

        var customerPointer = null;

        var fillModel = function(customer){
            var customerAddressString = "";
            if(customer.address){
                customerAddressString = (customer.address.street ? customer.address.street+", " : "")+(customer.address.zipCode ? customer.address.zipCode+" " : "")+(customer.address.city || "");
            }
            
            customer.addressString = customerAddressString;
        };

        var displayAlertMessage = function(serverResponse){
            var alertHtml = HowMuchUtilityService.createAlertMessage({
                type: serverResponse.resultType,
                title: serverResponse.resultType=="success" ? "All right!" : "Ops!",
                message: serverResponse.msg,//"I testi degli errori non sono ancora stati implementati",
                isDismissable: true,
                code: serverResponse.status
            });

            $("#alertsBox").append(alertHtml);

            window.setTimeout(function(){
                $('#alertsBox .alert-success').slideUp(function(){
                    $(this).remove();
                });
            }, 5000);
        };

        var resetCustomerModel = function(){
            self.scope.customerModel = {
                name: "",
                address: "",
                piva: "",
                eur_h: ""
            };
        };
        
        var getAllCustomers = function(){
            var response = CustomerService.query();
            response.$promise.then(function(resp) {
                console.log(resp);
                for(var i in resp.data){
                    fillModel(resp.data[i]);
                }

                self.scope.items = resp.data || [];

                //alert(resp.data);
            });
        };
        
        var addNewCustomer = function(customer){
            var response = CustomerService.create(customer);
            response.$promise.then(function(resp){
                if(resp.status==0) {
                    resp.resultType = "success";
                    resetCustomerModel();

                    fillModel(resp.data[0]);
                    self.scope.items.push(resp.data[0]);
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };
        
        var updateCustomer = function(customer){
            var response = CustomerService.update(customer);
            response.$promise.then(function(resp){
                console.log(resp);

                if(resp.status==0) {
                    resp.resultType = "success";

                    fillModel(resp.data[0]);
                    HowMuchUtilityService.synchronizeModel(customerPointer, resp.data[0]);

                    self.scope.resetEditSelection();
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };
        
        var removeCustomer = function(customerId){
            var response = CustomerService.delete({key:customerId});
            response.$promise.then(function(resp){
                console.log(resp);

                if(resp.status==0) {
                    resp.resultType = "success";
                    //self.scope.items = resp.data || [];
                    self.scope.items = self.scope.items.filter(function(element){
                        return element.key != customerId;
                    });
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };
        
        setMenuItemActive("customers");

        getAllCustomers();
        
        self.scope.saveCustomer = function(customer){
            addNewCustomer(customer);
        };
        
        self.scope.editCustomer = function(customer){
            updateCustomer(customer);
        };
        
        self.scope.trashCustomer = function(customerId){
            noty({
                type: "confirm",
                layout: "center",
                text: self.filter('translate')("The selected customer will be deleted. Continue?"),
                modal: true,
                timeout: false,
                dismissQueue: false,
                buttons: [
                    {
                        addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {

                            $noty.close();
                            removeCustomer(customerId);
                        }
                    },
                    {
                        addClass: 'btn btn-danger', text: self.filter('translate')('Cancel'), onClick: function ($noty) {
                            $noty.close();
                        }
                    }
                ]
            });
        };
        
        self.scope.prepareForEdit = function(customer){
            self.scope.isInEditMode = true;

            self.scope.customerModel = HowMuchUtilityService.cloneModel(customer);
            customerPointer = customer;

            self.scope.formTitle = self.filter('translate')('Edit')+' '+customer.name;

            self.scope.isFormOpen = true;
        };

        self.scope.resetEditSelection = function(){
            resetCustomerModel();
            self.scope.formTitle = self.filter('translate')("Add a new customer");

            self.scope.isInEditMode = false;

            customerPointer = null;
        };

        self.scope.sum = function(lst) {
            var sm = 0;
            for(var i=0; i<lst.length; i++)
                sm += lst[i].value;
            return sm;
        };

        self.scope.filterOptions = {
            filterText: ''
        };
        
        var aggregateTemplate = "<div ng-click=\"row.toggleExpand()\" ng-style=\"rowStyle(row)\" class=\"ngAggregate\">" +
        "    <span class=\"ngAggregateText\"><span class='ngAggregateTextLeading'>{{row.label CUSTOM_FILTERS}} {{row.totalChildren()}} {{entryMaybePlural(row)}}</span></span>" +
        "    <div class=\"{{row.aggClass()}}\"></div>" +
        "</div>" +
        "";

        var actionsColumnTemplate = '<a id="editCustomer" title="'+self.filter('translate')('Edit this customer')+'" class="action_button fa fa-edit" ng-click="prepareForEdit(row.entity)"></a>'+
        '<a id="deleteCustomer" title="'+self.filter('translate')('Trash this customer')+'" class="action_button fa fa-trash-o" ng-click="trashCustomer(row.entity.key)"></a>';
        
        self.scope.gridOptions = { 
            data: 'items',
            showGroupPanel: true,
            enableCellSelection: false,
            enableRowSelection: false,
            showSelectionCheckbox: false,
            enableCellEdit: false,
            keepLastSelected: false,
            enableColumnReordering: true,
            enableColumnResize: true,
            showColumnMenu: true,
            filterOptions: self.scope.filterOptions,
            selectedItems: self.scope.mySelections,
            aggregateTemplate: aggregateTemplate,
            columnDefs: [{field: 'name', displayName: self.filter('translate')('Name')}, 
                        //{field: 'name', displayName: 'Name', enableCellEdit: true, cellFilter: "currency: '€'", cellClass: "getRowClass(value)"}, 
                         {field: 'addressString', displayName: self.filter('translate')('Address')},
                         {field: 'piva', displayName: self.filter('translate')('VAT number')},
                         {field: 'eur_h', displayName: '€/h', cellFilter: "currency: '€'"},
                         //{field: 'getDirection()', displayName: 'Direzione', enableCellEdit: false},
                         {field: 'last_operation', displayName: self.filter('translate')('Last Operation'), cellFilter: 'date:\'EEE dd/MM/yyyy, HH:mm\''},
                         {displayName:self.filter('translate')('Actions'),cellTemplate:actionsColumnTemplate, width: 70}],
          plugins: [new ngGridCsvExportPlugin()],
          showFooter: true
        };

        /*$scope.edit = function edit(row){
            console.log("Here I need to know which button was selected " + row.entity.name)
        }*/
        
        /* Utilities per la table */
        
        /*angular.forEach($scope.myData, function (row) {
          row.getDirection = function () {
            return row.value>=0 ? "+" : "-";
          };
        });*/
        
        self.scope.entryMaybePlural = function (row) {
          if(row.children.length==1)
            return "elemento";
          else
            return "elementi";
        };
        
        self.scope.aggSum = function (row) {
          var total = 0;
          angular.forEach(row.children, function(sub) {
            total += sub.entity.value;
          });
          return total.toString();
        };
        
        self.scope.getRowClass = function(row) {
          return row.entity.value >= 0 ? "positive" : "negative";
        }
    }
]);

/*--------------- Project Controller ------------------*/
angular.module('howMuch.controllers').controller('ProjectController', [
    '$scope', '$http', '$filter', '$location', 'ProjectService', 'HowMuchUtilityService',
    function($scope, $http, $filter, $location, ProjectService, HowMuchUtilityService){
        var self = this;
    
        self.scope = $scope;
        self.http = $http;
        self.filter = $filter;
        self.location = $location;

        self.scope.items = [];

        self.scope.isFormOpen = false;
        self.scope.formTitle = self.filter('translate')("Add a new project");
        self.scope.projectModel = {
            name: "",
            customer: "",
            eur: "",
            unatantum: ""
        };

        var projectPointer = null;

        var fillModel = function(project) {
            project.unatantumString = parseInt(project.unatantum,10) ? "a progetto" : "orario";
            project.customerName = self.scope.customerDict[project.customer];

            if (project.progress_work < 50) {
                project.progress_work_type = 'danger';
            } else if (project.progress_work < 75) {
                project.progress_work_type = 'warning';
            } else if (project.progress_work < 100) {
                project.progress_work_type = 'success';
            } else {
                project.progress_work_type = 'info';
            }

            return project; // utile solo per eventuali concatenazioni in stile jQuery
        };

        self.scope.customerList = [];
        self.scope.customerDict = {};
        var getCustomerListForProject = function(){
            self.http.get("/customers/small").success(function(response){
                self.scope.customerList = response.data;
                self.scope.customerDict = {};
                for(var i=0; i<response.data.length; i++) {
                    self.scope.customerDict[response.data[i].key] = response.data[i].name;
                }

                getAllProjects();
            });
        };
        getCustomerListForProject();

        self.scope.isInEditMode = false;

        var displayAlertMessage = function(serverResponse){
            var alertHtml = HowMuchUtilityService.createAlertMessage({
                type: serverResponse.resultType,
                title: serverResponse.resultType=="success" ? "All right!" : "Ops!",
                message: serverResponse.msg,//"I testi degli errori non sono ancora stati implementati",
                isDismissable: true,
                code: serverResponse.status
            });

            $("#alertsBox").append(alertHtml);

            window.setTimeout(function(){
                $('#alertsBox .alert-success').slideUp(function(){
                    $(this).remove();
                });
            }, 5000);
        };

        var resetProjectModel = function(){
            self.scope.projectModel = {
                name: "",
                customer: "",
                eur: "",
                unatantum: ""
            };
        };
        
        var getAllProjects = function(){
            var response = ProjectService.query();
            response.$promise.then(function(resp) {
                console.log(resp);
                self.scope.items = resp.data || [];

                for(var i=0; i<self.scope.items.length; i++) {
                    fillModel(self.scope.items[i]);
                }
                //alert(resp.data);
            });
        };
        
        var addNewProject = function(project){
            var response = ProjectService.create(project);
            response.$promise.then(function(resp){
                if(resp.status==0) {
                    resp.resultType = "success";
                    resetProjectModel();

                    fillModel(resp.data[0]);

                    self.scope.items.push(resp.data[0]);
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };
        
        var updateProject = function(project){
            var response = ProjectService.update(project);
            response.$promise.then(function(resp){
                console.log(resp);

                if(resp.status==0) {
                    resp.resultType = "success";
                    HowMuchUtilityService.synchronizeModel(projectPointer, resp.data[0]);

                    fillModel(projectPointer);

                    self.scope.resetEditSelection();
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };
        
        var removeProject = function(projectId){
            var response = ProjectService.delete({key:projectId});
            response.$promise.then(function(resp){
                console.log(resp);

                if(resp.status==0) {
                    resp.resultType = "success";
                    self.scope.items = self.scope.items.filter(function(element){
                        return element.key != projectId;
                    });
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };
        
        setMenuItemActive("projects");

        //getAllProjects(); Messa come callback al recupero delle aziende, o l'asincronia può portare a non avere i dati necessari per tempo!
        
        self.scope.saveProject = function(project){
            //console.log(project);
            addNewProject(project);
        };
        
        self.scope.editProject = function(project){
            updateProject(project);
        };
        
        self.scope.trashProject = function(projectId){
            noty({
                type: "confirm",
                layout: "center",
                text: self.filter('translate')("The selected project will be deleted. Continue?"),
                modal: true,
                timeout: false,
                dismissQueue: false,
                buttons: [
                    {
                        addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {

                            $noty.close();
                            removeProject(projectId);
                        }
                    },
                    {
                        addClass: 'btn btn-danger', text: self.filter('translate')('Cancel'), onClick: function ($noty) {
                            $noty.close();
                        }
                    }
                ]
            });
        };

        self.scope.invoiceProject = function(project){
            noty({
                type: "confirm",
                layout: "center",
                text: self.filter('translate')("Invoicing this project you will be redirected to the invoice page. Continue?"),
                modal: true,
                timeout: false,
                dismissQueue: false,
                buttons: [
                    {
                        addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {

                            $noty.close();
                            self.location.path("/invoices/"+project);
                            self.scope.$apply();
                        }
                    },
                    {
                        addClass: 'btn btn-danger', text: self.filter('translate')('Cancel'), onClick: function ($noty) {
                            $noty.close();
                        }
                    }
                ]
            });
        };

        self.scope.prepareForEdit = function(project){
            self.scope.isInEditMode = true;

            self.scope.projectModel = HowMuchUtilityService.cloneModel(project);
            projectPointer = project;

            self.scope.formTitle = self.filter('translate')('Edit')+' '+project.name;

            if(!self.scope.isFormOpen){
                self.scope.isFormOpen = true;
            }
        };

        self.scope.resetEditSelection = function(){
            resetProjectModel();
            self.scope.formTitle = self.filter('translate')("Add a new project");

            self.scope.isInEditMode = false;

            projectPointer = null;
        };

        self.scope.sum = function(lst) {
            var sm = 0;
            for(var i=0; i<lst.length; i++)
                sm += lst[i].value;
            return sm;
        };

        self.scope.filterOptions = {
          filterText: ''
        };

        var progressColumnTemplate = '' +
            '<progressbar value=row.getProperty("progress_work") max=100 type={{row.getProperty("progress_work_type")}}><span style="color:black; white-space:nowrap;">{{row.getProperty("progress_work")}} / 100</span></progressbar>';
        
        var actionsColumnTemplate = '' +
            '<a id="editProject" title="'+self.filter('translate')('Edit this project')+'" class="action_button fa fa-edit" ng-click="prepareForEdit(row.entity)"></a>'+
            '<a id="deleteProject" title="'+self.filter('translate')('Trash this project')+'" class="action_button fa fa-trash-o" ng-click="trashProject(row.entity.key)"></a>' +
            //'<a id="invoiceProject" ng-show="row.getProperty(\'progress_work\')==100 && !isInEditMode" title="Invoice this project" class="action_button fa fa-file-pdf-o" ng-click="invoiceProject(row.entity.key)"></a>';
            '<a id="invoiceProject" ng-show="row.getProperty(\'progress_work\')==100 && !isInEditMode" title="'+self.filter('translate')('Invoice this project')+'" class="action_button fa fa-credit-card" ng-click="invoiceProject(row.entity.key)"></a>';

        var aggregateTemplate = "<div ng-click=\"row.toggleExpand()\" ng-style=\"rowStyle(row)\" class=\"ngAggregate\">" +
        "    <span class=\"ngAggregateText\"><span class='ngAggregateTextLeading'>{{row.label CUSTOM_FILTERS}} {{row.totalChildren()}} {{entryMaybePlural(row)}}</span></span>" +
        "    <div class=\"{{row.aggClass()}}\"></div>" +
        "</div>" +
        "";
        
        self.scope.gridOptions = { 
            data: 'items',
            showGroupPanel: true,
            enableCellSelection: false,
            enableRowSelection: false,
            showSelectionCheckbox: false,
            enableCellEdit: false,
            filterOptions: $scope.filterOptions,
            selectedItems: $scope.mySelections,
            keepLastSelected: false,
            enableColumnReordering: true,
            enableColumnResize: true,
            showColumnMenu: true,
            aggregateTemplate: aggregateTemplate,
            columnDefs: [{field: 'name', displayName: self.filter('translate')('Name')},
                         {field: 'customerName', displayName: self.filter('translate')('Customer')},
                         //{field: 'eur', displayName: 'Compenso', cellFilter: "currency: '€'"},
                         //{field: 'unatantum', displayName: 'Tipo compenso'},
                         //{field: 'getUnaTantumLabel(row.entity.unatantum)', displayName:'Tipo compenso'},
                         {field: 'unatantumString', displayName:self.filter('translate')('Project payment type')},
                         {displayName:self.filter('translate')('Development progress'),cellTemplate:progressColumnTemplate, width: 300},
                         {field: 'last_operation', displayName: self.filter('translate')('Last Operation'), cellFilter: 'date:\'EEE dd/MM/yyyy, HH:mm\''},
                         {displayName:self.filter('translate')('Actions'),cellTemplate:actionsColumnTemplate, width: 100}],
          plugins: [new ngGridCsvExportPlugin()],
          showFooter: true
        };
        
        /* Utilities per la table */
        
        self.scope.entryMaybePlural = function (row) {
          if(row.children.length==1)
            return "elemento";
          else
            return "elementi";
        };
        
        self.scope.aggSum = function (row) {
          var total = 0;
          angular.forEach(row.children, function(sub) {
            total += sub.entity.value;
          });
          return total.toString();
        };
        
        self.scope.getRowClass = function(row) {
          return row.entity.value >= 0 ? "positive" : "negative";
        }
    }
]);

/*--------------- Work Session Controller ------------------*/
angular.module('howMuch.controllers').controller('WorkSessionController', [
    '$scope', '$http', '$filter',
    function($scope, $http, $filter){
        var self = this;
    
        self.scope = $scope;
        self.http = $http;
        self.filter = $filter;
        
        setMenuItemActive("sessions");
        
        self.scope.items = [];
    }
]);

/*--------------- Invoice Controller ------------------*/
angular.module('howMuch.controllers').controller('InvoiceController', [
    '$scope', '$http', '$filter', '$routeParams', 'InvoiceService', 'HowMuchUtilityService',
    function($scope, $http, $filter, $routeParams, InvoiceService, HowMuchUtilityService){
        var self = this;
    
        self.scope = $scope;
        self.http = $http;
        self.filter = $filter;
        self.routeParams = $routeParams;
        
        setMenuItemActive("invoices");
        
        self.scope.items = [];
        self.scope.isFormOpen = false;
        self.scope.formTitle = "Add a new invoice";
        self.scope.invoiceModel = {
            project: null,
            amount: null,
            additionals: [],
            rows: [
                {
                    description: "",
                    amount: 0.00
                }
            ]
        };

        self.scope.additionalTaxes = [];

        var invoicePointer = null;

        var createInvoiceRow = function(){
            return {
                description: "",
                amount: 0.00
            };
        };

        var fillModel = function(invoice) {
            invoice.projectName = self.scope.projectDict[invoice.project];

            invoice.extra = "";
            if(invoice.additionals.length > 0){
                for(var i = 0; i < invoice.additionals.length; i++){
                    var additionalTax = invoice.additionals[i];

                    if(i > 0){
                        invoice.extra += ",";
                    }
                    invoice.extra += additionalTax.name;
                }
            }

            return invoice; // utile solo per eventuali concatenazioni in stile jQuery
        };

        var checkPreFilledInvoice = function(){
            if(self.routeParams.projectId){
                self.scope.invoiceModel.project = self.routeParams.projectId;
                self.scope.isFormOpen = true;
            }
        };
        checkPreFilledInvoice();

        var resetInvoiceModel = function(){
            self.scope.invoiceModel = {
                project: null,
                amount: null,
                additionals: [],
                rows: [
                    {
                        description: "",
                        amount: 0.00
                    }
                ]
            };

            resetAdditionalTaxes();
        };

        var getTotalAmountForInvoice = function(){
            var totalAmount = 0.0;

            for(var i in self.scope.invoiceModel.rows){
                var invoiceRow = self.scope.invoiceModel.rows[i];

                totalAmount += invoiceRow.amount;
            }

            return totalAmount;
        };

        var getAdditionalTaxesForInvoice = function(){
            self.http.get("/invoice/settings/taxes").success(function(response){
                if(response.status == 0){
                    self.scope.additionalTaxes = response.data;
                }
            });
        };
        getAdditionalTaxesForInvoice();

        var setAdditionalTaxes = function(modelTaxes){
            for(var i in self.scope.additionalTaxes){
                for(var j in modelTaxes){
                    var tax = modelTaxes[j];
                    if(self.scope.additionalTaxes[i].key == tax.key){
                        self.scope.additionalTaxes[i].selected = true;
                        break;
                    }
                }
            }
        };

        var resetAdditionalTaxes = function(){
            for(var i in self.scope.additionalTaxes){
                self.scope.additionalTaxes[i].selected = false;
            }
        }

        self.scope.projectList = [];
        self.scope.projectDict = {};
        var getProjectListForInvoice = function(){
            self.http.get("/projects/small").success(function(response){
                self.scope.projectList = response.data;
                self.scope.projectDict = {};
                if(response.data) {
                    for(var i=0; i<response.data.length; i++) {
                        self.scope.projectDict[response.data[i].key] = response.data[i].name;
                    }
                }

                getAllInvoices();
            });
        };
        getProjectListForInvoice();

        var addNewInvoice = function(invoice){
            var response = InvoiceService.create(invoice);
            response.$promise.then(function(resp){
                if(resp.status==0) {
                    resp.resultType = "success";
                    resetInvoiceModel();

                    fillModel(resp.data[0]);

                    self.scope.items.push(resp.data[0]);
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };

        var displayAlertMessage = function(serverResponse){
            var alertHtml = HowMuchUtilityService.createAlertMessage({
                type: serverResponse.resultType,
                title: serverResponse.resultType=="success" ? "All right!" : "Ops!",
                message: serverResponse.msg,
                isDismissable: true,
                code: serverResponse.status
            });

            $("#alertsBox").append(alertHtml);

            window.setTimeout(function(){
                $('#alertsBox .alert-success').slideUp(function(){
                    $(this).remove();
                });
            }, 5000);
        };

        
        var getAllInvoices = function(){
            var response = InvoiceService.query();
            response.$promise.then(function(resp) {
                console.log(resp);
                self.scope.items = resp.data || [];

                for(var i=0; i<self.scope.items.length; i++) {
                    fillModel(self.scope.items[i]);
                }
                //alert(resp.data);
            });
        };
        
        
        var removeInvoice = function(projectId){
            var response = InvoiceService.delete({key:projectId});
            response.$promise.then(function(resp){
                console.log(resp);

                if(resp.status==0) {
                    resp.resultType = "success";
                    self.scope.items = self.scope.items.filter(function(element){
                        return element.key != projectId;
                    });
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };

        var updateInvoice = function(invoice){
            var response = InvoiceService.update(invoice);
            response.$promise.then(function(resp){
                console.log(resp);

                if(resp.status==0) {
                    resp.resultType = "success";

                    HowMuchUtilityService.synchronizeModel(invoicePointer, resp.data[0]);
                    fillModel(invoicePointer);

                    self.scope.resetEditSelection();
                    
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };

        self.scope.addNewInvoiceRow = function(){
            var row = createInvoiceRow();
            self.scope.invoiceModel.rows.push(row);
        };
        self.scope.removeInvoiceRow = function(itemIndex){
            if(self.scope.invoiceModel.rows.length > 1){
                self.scope.invoiceModel.rows.splice(itemIndex, 1);    
            }
        };

        self.scope.prepareForEdit = function(invoice){
            self.scope.isInEditMode = true;

            self.scope.invoiceModel = HowMuchUtilityService.cloneModel(invoice);
            setAdditionalTaxes(self.scope.invoiceModel.additionals);

            invoicePointer = invoice;

            self.scope.formTitle = 'Edit invoice';

            if(!self.scope.isFormOpen){
                self.scope.isFormOpen = true;
            }
        };

        self.scope.resetEditSelection = function(){
            resetInvoiceModel();
            self.scope.formTitle = "Add a new invoice";

            self.scope.isInEditMode = false;

            invoicePointer = null;
        };
        
        self.scope.trashInvoice = function(invoiceId){
            noty({
                type: "confirm",
                layout: "center",
                text: "The selected invoice will be deleted. Continue?",
                modal: true,
                timeout: false,
                dismissQueue: false,
                buttons: [
                    {
                        addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {

                            $noty.close();
                            removeInvoice(invoiceId);
                        }
                    },
                    {
                        addClass: 'btn btn-danger', text: 'Cancel', onClick: function ($noty) {
                            $noty.close();
                        }
                    }
                ]
            });
        };

        self.scope.saveInvoice = function(invoice){
            //console.log(project);
            addNewInvoice(invoice);
        };

        self.scope.editInvoice = function(invoice){
            //console.log(project);
            updateInvoice(invoice);
        };

        self.scope.printInvoice = function(invoiceId){
            //alert("Da implementare...");
            window.open('/invoices/preview/'+invoiceId,'_newtab');
        };

        self.scope.invoiceSent = function(invoiceId){
            alert("Da implementare...");
        };

        self.scope.invoicePaid = function(invoiceId){
            alert("Da implementare...");
        };

        self.scope.filterOptions = {
          filterText: ''
        };

        self.scope.refreshTotalAmount = function(){
            self.scope.invoiceModel.amount = getTotalAmountForInvoice();
        };

        var actionsColumnTemplate = '' +
            '<a id="editInvoice" title="Edit this invoice" class="action_button fa fa-edit" ng-click="prepareForEdit(row.entity)"></a>'+
            '<a id="deleteInvoice" title="Trash this invoice" class="action_button fa fa-trash-o" ng-click="trashInvoice(row.entity.key)"></a>' +
            '<a id="printInvoice" title="Print this invoice" class="action_button fa fa-print" ng-click="printInvoice(row.entity.key)"></a>' +
            '<a id="sentInvoice" title="This invoice is sent" class="action_button fa fa-paper-plane" ng-click="invoiceSent(row.entity.key)"></a>' +
            '<a id="paidInvoice" title="This invoice is paid" class="action_button fa fa-money" ng-click="invoicePaid(row.entity.key)"></a>';

        var aggregateTemplate = "<div ng-click=\"row.toggleExpand()\" ng-style=\"rowStyle(row)\" class=\"ngAggregate\">" +
        "    <span class=\"ngAggregateText\"><span class='ngAggregateTextLeading'>{{row.label CUSTOM_FILTERS}} {{row.totalChildren()}} {{entryMaybePlural(row)}}</span></span>" +
        "    <div class=\"{{row.aggClass()}}\"></div>" +
        "</div>" +
        "";
        
        self.scope.gridOptions = { 
            data: 'items',
            showGroupPanel: true,
            enableCellSelection: false,
            enableRowSelection: false,
            showSelectionCheckbox: false,
            enableCellEdit: false,
            filterOptions: $scope.filterOptions,
            selectedItems: $scope.mySelections,
            keepLastSelected: false,
            enableColumnReordering: true,
            enableColumnResize: true,
            showColumnMenu: true,
            aggregateTemplate: aggregateTemplate,
            columnDefs: [/*{field: 'customerName', displayName: 'Customer'},*/
                         {field: 'projectName', displayName: 'Project'},
                         {field: 'amount', displayName: 'Amount', cellFilter: "currency: '€'"},
                         {field: 'extra', displayName: 'Extra'},
                         {field: 'created_date', displayName: 'Data creazione', cellFilter: 'date:\'EEE dd/MM/yyyy, HH:mm\''},
                         {field: 'last_operation', displayName: 'Last operation', cellFilter: 'date:\'EEE dd/MM/yyyy, HH:mm\''},
                         /*{field: 'name', displayName: 'Data emissione', cellFilter: 'date:\'EEE dd/MM/yyyy, HH:mm\''},
                         {field: 'name', displayName: 'Data pagamento', cellFilter: 'date:\'EEE dd/MM/yyyy, HH:mm\''},*/
                         {displayName:'Actions',cellTemplate:actionsColumnTemplate, width: 200}],
          plugins: [new ngGridCsvExportPlugin()],
          showFooter: true
        };
        
        /* Utilities per la table */
        
        self.scope.entryMaybePlural = function (row) {
          if(row.children.length==1)
            return "elemento";
          else
            return "elementi";
        };
    }
]);

angular.module('howMuch.controllers').controller('SettingsController', [
    '$scope', '$http', 'UserService', 'InvoiceSettingsService', 'HowMuchUtilityService',
    function($scope, $http, UserService, InvoiceSettingsService, HowMuchUtilityService){
        var self = this;

        self.scope = $scope;
        self.http = $http;

        setMenuItemActive("settings");

        self.scope.tinymceOptions = {
            plugins: [
                "advlist autolink lists link image charmap print preview anchor",
                "searchreplace visualblocks code",
                "insertdatetime table contextmenu paste"
            ],
            toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
        };

        self.scope.userModel = {
            account_customers_limit: 0,
            account_projects_limit: 0,
            account_customers_count: 0,
            account_projects_count: 0
        };

        self.scope.invoiceSettingsModel = {};

        self.scope.isAccountFormOpen = true;
        self.scope.isUserFormOpen = false;
        self.scope.isSettingsFormOpen = false;

        var getUserInformation = function(){
            var response = UserService.find();
            response.$promise.then(function(resp){
                console.log(resp);

                self.scope.userModel = resp.data;
            });
        };

        getUserInformation();

        var createInvoiceTaxModel = function(){
            return {
                name: "",
                value: 0.0,
                type: "percentage"
            }; 
        };

        var getInvoiceSettings = function(){
            var response = InvoiceSettingsService.find();
            response.$promise.then(function(resp){
                console.log(resp);

                self.scope.invoiceSettingsModel = resp.data;

                var defaultInvoiceTax = createInvoiceTaxModel();
                self.scope.invoiceSettingsModel.invoiceTaxes.push(defaultInvoiceTax);
            });
        };

        var saveUserInformation = function(user){
            var response = UserService.update(user);
            response.$promise.then(function(resp){
                if(resp.status==0) {
                    resp.resultType = "success";
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };

        var saveInvoiceSettigs = function(invoiceSettings){
            var response = InvoiceSettingsService.update(invoiceSettings);
            response.$promise.then(function(resp){
                if(resp.status==0) {
                    resp.resultType = "success";
                } else {
                    resp.resultType = "danger";
                }
                
                displayAlertMessage(resp);
            });
        };

        var displayAlertMessage = function(serverResponse){
            var alertHtml = HowMuchUtilityService.createAlertMessage({
                type: serverResponse.resultType,
                title: serverResponse.resultType=="success" ? "All right!" : "Ops!",
                message: serverResponse.msg,
                isDismissable: true,
                code: serverResponse.status
            });

            $("#alertsBox").append(alertHtml);

            window.setTimeout(function(){
                $('#alertsBox .alert-success').slideUp(function(){
                    $(this).remove();
                });
            }, 5000);
        };

        self.scope.saveUserInformation = function(userModel){
            //userHandler.saveUserInformation(userModel);
            saveUserInformation(userModel);
        };
        self.scope.resetUserInformation = function(){
            self.scope.userModel = userHandler.getUserInformation();
        };

        self.scope.saveInvoiceSettings = function(invoiceSettingsModel){
            saveInvoiceSettigs(invoiceSettingsModel);
        };
        self.scope.resetInvoiceSettings = function(){
            getInvoiceSettings();
        };

        self.scope.addNewInvoiceTax = function(){
            var newInvoiceTax = createInvoiceTaxModel();
            self.scope.invoiceSettingsModel.invoiceTaxes.push(newInvoiceTax);
        };
        self.scope.removeInvoiceTax = function(itemIndex){
            if(self.scope.invoiceSettingsModel.invoiceTaxes.length > 1){
                self.scope.invoiceSettingsModel.invoiceTaxes.splice(itemIndex, 1);    
            }
        };

        getInvoiceSettings();
    }
]);